// pages/books/books.js
var api = require('../../config/api.js');
var util = require('../../utils/util.js');
var app = getApp();
var WxParse = require('../../wxParse/wxParse.js');
var is_loading_comment = false;
var is_more_comment = true;
var p = 1;
var pagesize = 1;
var size = 20;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id:1,
    book:{},
    comment_list: [],
    specificationList: [],
    imgUrl: api.RootUrl,
    show_attr_picker: false,//展开选择图书规格表
    noCollectImage: "/images/icon-favorite.png",
    hasCollectImage: "/images/icon-favorite-active.png",
    collectImage:'',
    collectName:'',
    userHasCollect: 0,//用户有没有关注，0为没有 1为有
    cartBookCount: 0,
    service_list: [
      { name: '假一赔十' },
      { name: '仅供参考' },
      { name: '7天无理由退货' },
      { name: '快递/货到付款' },
    ],
    form: {
      number: 1,
    },
    comment_count: {
      allstar: 0,
      good: 0,
      middle: 0,
      bad: 0,
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      id: parseInt(options.id)
      // id: 1181000
    });
    let that = this;
    that.getBook();
    that.getCommentList();
    //获取购物车数量
    util.request(api.CartBookCount).then(function (res) {
      if (res.errno === 0) {
        that.setData({
          cartBookCount: res.data.cartTotal.bookCount
        });

      }
    });
  },

  //获取图书
  getBook: function () {  
    let that = this;
    util.request(api.BooksDetail,{id:that.data.id },'POST').then(function(res){
      if(res.errno === 0){
        that.setData({
          book: res.data.bookInfo,
          specificationList: res.data.specificationList,
          userHasCollect: res.data.userHasCollect,
          tab_detail:"active",
        });
        if (res.data.userHasCollect === 1) {
          that.setData({
             collectImage: that.data.hasCollectImage,
             collectName: '已收藏',
          });
        } else {
          that.setData({
             collectName: '收藏',
             collectImage: that.data.noCollectImage
          });
        }
        console.log(res.data.specificationList);
        WxParse.wxParse("detail", "html", res.data.bookInfo.detail, that);
       
      }
    });
  },

  //获取评论
  getCommentList: function (more) {
    let that = this;
    if (more && that.data.tab_comment != "active")
      return;
    if (is_loading_comment)
      return;
    if (!is_more_comment)
      return;
    is_loading_comment = true;
    util.request(api.CommentList, {bookId:that.data.id,page:p,size:size},'post').then(function(res){
      if (res.errno === 0) {
        is_loading_comment = false;
        p++;

        for (var i = 0; i < res.data.commentList.list.length; i++) {
          res.data.commentList.list[i].createTime = util.formatTime(res.data.commentList.list[i].createTime);
        }

        that.setData({
          comment_count: res.data.commentCounts,
          comment_list: more ? that.data.comment_list.concat(res.data.commentList.list) : res.data.commentList.list,
        });
        
        if (res.data.commentList.length == 0)
          is_more_comment = false;
      }
    }) 
},

  //评论详情切换
  tabSwitch: function (e) {
    var that = this;
    var tab = e.currentTarget.dataset.tab; //页面定义data-名字
    if (tab == "detail") {
      that.setData({
        tab_detail: "active",
        tab_comment: "",
      });
    } else {
      that.setData({
        tab_detail: "",
        tab_comment: "active",
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this;
    that.getBook();
    that.getCommentList();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let that = this;
    that.getCommentList(true);
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var page = this;
    var user_info = wx.getStorageSync("user_info");
    var res = {
      path: "/pages/goods/goods?id=" + this.data.id + "&user_id=" + user_info.id,
      success: function (e) {
        console.log(e);
        share_count++;
        if (share_count == 1)
          app.shareSendCoupon(page);
      },
      title: page.data.goods.name,
      imageUrl: page.data.goods.pic_list[0].pic_url,
    };
    return res;
  },
  //图书-
  numberSub: function () {
    var page = this;
    var num = page.data.form.number;
    if (num <= 1)
      return true;
    num--;
    page.setData({
      form: {
        number: num,
      }
    });
  },
  //图书+
  numberAdd: function () {
    var page = this;
    var num = page.data.form.number;
    num++;
    page.setData({
      form: {
        number: num,
      }
    });
  },
  //图书数 输入
  numberBlur:function(e){
    var that = this;
    var num = e.detail.value;
    num = parseInt(num);
    if (isNaN(num))
      num = 1;
    if (num <= 0)
      num = 1;
    that.setData({
      form: {
        number: num,
      }
    });
  },

  //加入购物车
  addCart: function () {
    this.submit('ADD_CART');
  },
  
  //立即购买
  buyNow: function () {
    this.submit('BUY_NOW');
  },

  //确认购买
  submit: function (type) {
    let that = this;
    if (!that.data.show_attr_picker){
      that.setData({
        show_attr_picker:true,
      });
      return true;
    }
    //超过库存量
    if (that.data.form.number > that.data.book.storage){
      wx.showToast({
        title: '图书库存不足，请选择其他数量',
        image:'/images/icon-warning.png',
      });
      return true;
    }

    var specificationList = that.data.specificationList;
    var checked_specification_list = [];
    for (var i in specificationList) {
      var specification = false;
      //系列下的列表
      for(var j in specificationList[i].valueList){
        if (specificationList[i].valueList[j].checked) {
          specification = {
            id: specificationList[i].valueList[j].id,
            value: specificationList[i].valueList[j].value,
          };
          break;
        }   
      }
      if (!specification){
        wx.showToast({
          title: "请选择" + specificationList[i].name,
          image: "/images/icon-warning.png",
        });
        return true;
      }else{
        checked_specification_list.push({
          specificationId: specificationList[i].specificationId,
          name: specificationList[i].name,
          id: specification.id,
          value: specification.value,
        });
      }

    }

    if (type == 'ADD_CART') {//加入购物车
      wx.showLoading({
        title: "正在提交",
        mask: true,
      });
      util.request(api.CartAdd,{
          bookId: that.data.id,
          specificationInfo: JSON.stringify(checked_specification_list),
          num: that.data.form.number,
        },'post').then(function(res){
          if(res.errno==0){
            wx.showToast({
              title: res.errmsg,
              duration: 1500
            });
            wx.hideLoading();
            that.setData({
              show_attr_picker: false,
            });
          }
        });
    }
    if (type == 'BUY_NOW') {//立即购买
      that.setData({
        show_attr_picker: false,
      });
      
      wx.navigateTo({
        url: "/pages/order-submit/order-submit?bookInfo=" + JSON.stringify({
          bookId: that.data.id,
          specificationInfo: checked_specification_list,
          num: that.data.form.number,
        }),
      });
    }

  },

  //选择规格
  attrClick: function (e) {
    let that = this;
    let specificationId = e.target.dataset.specificationId;
    let valueId = e.target.dataset.valueId;
    let specificationList = this.data.specificationList;
    let book = this.data.book;
    for (var i in specificationList) {
      if (specificationList[i].specificationId != specificationId)
        continue;
      for (var j in specificationList[i].valueList) {
        if (specificationList[i].valueList[j].id == valueId) {
          specificationList[i].valueList[j].checked = true;
          book.unitPrice = specificationList[i].valueList[j].price;
          book.num = specificationList[i].valueList[j].price;
        } else {
          specificationList[i].valueList[j].checked = false;
        }
      }
    }
    that.setData({
      specificationList: specificationList,
      book:book,
    });
  },
  
  


  //关闭规格视图
  hideAttrPicker: function () {
    var page = this;
    page.setData({
      show_attr_picker: false,
    });
  },
  //开启规格视图
  showAttrPicker: function () {
    var page = this;
    page.setData({
      show_attr_picker: true,
    });
  },
  //添加删除收藏
  favoriteAddOrRemove: function () {
    let that = this;
    util.request(api.CollectAddOrDelete, { bookId: that.data.book.id},'POST').then(function(res){
      if(res.errno === 0){
        if (res.data.type == 'add') {
          that.setData({
            collectName:'已收藏',
            collectImage: that.data.hasCollectImage
          });
        } else {
          that.setData({
            collectName: '收藏',
            collectImage: that.data.noCollectImage
          });
        }
      }
    });
  },

  //以下是海报、分享的模块
  showShareModal: function () {
    var page = this;
    page.setData({
      share_modal_active: "active",
      no_scroll: true,
    });
  },

  shareModalClose: function () {
    var page = this;
    page.setData({
      share_modal_active: "",
      no_scroll: false,
    });
  },

  getBookCode: function () {
    let that = this;
    that.setData({
      book_code_active:"active",
      share_modal_active:"",
    });
    if (that.data.bookCodePic)
      return true;
    that.setData({
      bookCodePic: that.data.imgUrl+that.data.book.pic,
    });
    console.log(that.data.bookCodePic);
  },

  closeBookCode: function () {
    var page = this;
    page.setData({
      book_code_active: "",
      no_scroll: false,
    });
  },

  clickBookCode: function (e) {
    var src = e.currentTarget.dataset.src;
    wx.previewImage({
      urls: [src],
    });
  },

  saveBookCode: function () {
    var page = this;
    //需要授权
    if (!wx.saveImageToPhotosAlbum) {
      // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。',
        showCancel: false,
      });
      return;
    }

    wx.showLoading({
      title: "正在保存图片",
      mask: false,
    });

    wx.downloadFile({
      url: page.data.bookCodePic,
      success: function (e) {
        wx.showLoading({
          title: "正在保存图片",
          mask: false,
        });
        wx.saveImageToPhotosAlbum({
          filePath: e.tempFilePath,
          success: function () {
            wx.showModal({
              title: '提示',
              content: '商品海报保存成功',
              showCancel: false,
            });
          },
          fail: function (e) {
            wx.showModal({
              title: '图片保存失败',
              content: e.errMsg,
              showCancel: false,
            });
          },
          complete: function (e) {
            console.log(e);
            wx.hideLoading();
          }
        });
      },
      fail: function (e) {
        wx.showModal({
          title: '图片下载失败',
          content: e.errMsg + ";" + page.data.bookCodePic,
          showCancel: false,
        });
      },
      complete: function (e) {
        console.log(e);
        wx.hideLoading();
      }
    });

  },
  

})